import React, { useState, useCallback, useEffect } from 'react';
import { connect } from 'umi';
import { Form, Card, DatePicker, Table, message } from 'antd';

import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { AdvancedSearch } from '@/components';
import Pagination from '@/components/Pagination';
import { SearchInput } from '@/components/UserForm';
import { isSuccess } from '@/utils/request';
import { logService } from '@/services/salaryManage/salaryCalculate';
import { queryLogOperator } from '@/services/salaryManage/salaryCommon';

import EmptyPlaceHolder from '@/pages/SalaryManage/components/EmptyPlaceHolder';
import { logBusiUnit } from '@/pages/SalaryManage/enum';
import { pageTabProps } from '@/pages/SalaryManage/utils';
import { OrganizationNameHead } from '@/pages/SalaryManage/components/OrganizationName';

const { RangePicker } = DatePicker;
const Page = ({ form, organizationCode }) => {
    const { getFieldDecorator } = form;

    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10
    });
    const [dataSource, setDataSource] = useState([]);
    const [loading, setLoading] = useState(false);

    const columns = [
        {
            dataIndex: 'operateTime',
            title: '操作时间',
            width: '30%',
            render: text => <EmptyPlaceHolder value={text} />
        },
        {
            dataIndex: 'employeeName',
            title: '操作人',
            width: '30%',
            render: text => <EmptyPlaceHolder value={text} />
        },
        {
            dataIndex: 'content',
            title: '操作内容描述',
            render(text) {
                return (
                    <span
                        style={{
                            display: 'inline-block',
                            whiteSpace: 'break-spaces',
                            wordBreak: 'break-all'
                        }}
                    >
                        <EmptyPlaceHolder value={text} />
                    </span>
                );
            }
        }
    ];

    /**
     * 查询
     */
    const search = useCallback(
        async pg => {
            setLoading(true);

            const formValues = form.getFieldsValue();
            const pageVo = pg || { ...pagination, current: 1 };
            const postData = {
                ...formValues,
                startDate: formValues?.time?.[0] ? formValues.time[0].format('YYYY-MM-DD') : null,
                endDate: formValues?.time?.[1] ? formValues.time[1].format('YYYY-MM-DD') : null,
                busiUnit: logBusiUnit.SETTING_SALARY_SPECIAL_LOG,
                organizationCode,
                page: {
                    pageNo: pageVo.current || 1,
                    pageSize: pageVo.pageSize || 10
                }
            };
            const response = await logService.querySysOperateLog(postData);
            if (!isSuccess(response)) {
                message.error(response.msg);
                setLoading(false);
                return;
            }

            setLoading(false);

            const { pageSize, total, pageNo: current, rows } = response.data;

            setPagination({
                ...pagination,
                pageSize: pageSize || 10,
                current: current || 1,
                total
            });
            setDataSource(rows);
        },
        [form, pagination, organizationCode]
    );

    const handleReset = () => {
        form.resetFields();
    };

    const tablePageChange = ({ current, pageSize }) => {
        search({
            ...pagination,
            current: current || pagination.current,
            pageSize: pageSize || pagination.pageSize
        });
    };

    useEffect(() => {
        search();
    }, []);

    return (
        <PageHeaderWrapper type="success">
            <Card
                bordered={false}
                title="操作日志"
                {...pageTabProps()}
                extra={<OrganizationNameHead organizationCode={organizationCode} />}
            >
                <AdvancedSearch form={form} onSubmit={search} onReset={handleReset}>
                    <Form.Item label="操作时间">
                        {getFieldDecorator('time', {})(<RangePicker placeholder="开始时间-结束时间" />)}
                    </Form.Item>
                    <Form.Item label="操作人">
                        {getFieldDecorator(
                            'employeeCode',
                            {}
                        )(
                            <SearchInput
                                params={{
                                    organizationCode
                                }}
                                getData={async params => {
                                    if (!params.organizationCode) {
                                        return [];
                                    }
                                    const employeeResponse = await queryLogOperator({
                                        organizationCode: params.organizationCode
                                    });
                                    return isSuccess(employeeResponse) ? employeeResponse.data || [] : [];
                                }}
                                selectProps={{
                                    placeholder: '请输入员工姓名',
                                    allowClear: true
                                }}
                                fieldsName={{
                                    value: 'employeeCode',
                                    title: 'employeeName'
                                }}
                            />
                        )}
                    </Form.Item>
                </AdvancedSearch>
                <div>
                    <Table
                        rowKey="operateLogId"
                        columns={columns}
                        dataSource={dataSource}
                        loading={loading}
                        pagination={false}
                    />
                    <Pagination {...pagination} onChange={tablePageChange} />
                </div>
            </Card>
        </PageHeaderWrapper>
    );
};

export default connect((state, { location }) => ({
    organizationCode: location?.query?.organizationCode
}))(Form.create()(Page));
